package com.sunlong.jiangwei.elasticsearch;

import com.sunlong.jiangwei.entity.JwSpu;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

@Service
public class JwSpuESService {

    @Autowired
    private JwSpuESDao spuESDao;

    /**
     * 根据属性筛选信息
     *
     * @param
     * @return
     */
    public List<Long> getList(String searchText, Integer page, Integer size) {
        if (StringUtils.isEmpty(searchText)){
            ArrayList<Long> list = new ArrayList<>();
            Iterable<JwSpu> all = spuESDao.findAll();
            for (JwSpu spu : all) {
                list.add(spu.getSpuId());
            }
            return list;
        }
        //spuTitle
        HashSet<JwSpu> jwSpuHashSet = new HashSet<>();
        queryToSet(searchText, "spuTitle", jwSpuHashSet);
        queryToSet(searchText, "spuSubTitle", jwSpuHashSet);
        queryToSet(searchText, "categoryName", jwSpuHashSet);
        queryToSet(searchText, "storeName", jwSpuHashSet);
        ArrayList<Long> longs = new ArrayList<>();
        for (JwSpu spu : jwSpuHashSet) {
            longs.add(spu.getSpuId());
        }
        return longs;
    }

    private HashSet<JwSpu> queryToSet(String searchText, String type, HashSet<JwSpu> jwSpuHashSet) {
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        NativeSearchQueryBuilder builder =  queryBuilder.withQuery(QueryBuilders.matchQuery(type, searchText));
        Page<JwSpu> search = spuESDao.search(builder.build());
        Iterator<JwSpu> iterator = search.iterator();
        while (iterator.hasNext()) {
            JwSpu next = iterator.next();
            System.out.println(next);
            jwSpuHashSet.add(next);
        }
        return jwSpuHashSet;
    }
}
